package com.finalproject.cloudnative06.controller;

import io.micrometer.core.instrument.Counter;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GetController {

    private final RedissonClient redissonClient;
    private final Counter counter;

    public GetController(RedissonClient redissonClient, Counter counter) {
        this.redissonClient = redissonClient;
        this.counter = counter;
    }

    @Value("${POD_NAME}")
    private String podName;

    @GetMapping("/check")
    public ResponseEntity<String> getResource() {
        counter.increment();
        RRateLimiter rateLimiter = redissonClient.getRateLimiter("resourceLimiter");
        if (!rateLimiter.isExists()){
            // 100token per sec
            rateLimiter.trySetRate(RateType.OVERALL, 100, 1, RateIntervalUnit.SECONDS);
        }

        boolean permitAcquired = rateLimiter.tryAcquire();
        if (!permitAcquired) {
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("Rate limit exceeded");
        }

        return ResponseEntity.ok("Success " + podName);
    }

    public int addI(int a, int b){
        return a+b;
    }

}
